<?php
namespace app\api\common;
use think\Config;
use think\Db;

class Program
{
    /**
     * 获取小程序AccessToken
     */
    public static function getAccessToken()
    {
        //获取access_token
        $config = Config::get("parameter.xcx_config");
        $appid = $config['wx_app_id'];
        $secret = $config['wx_app_secret'];
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $lifeTime = 2 * 3000;
        $xcxConfig = Db::name('xcx_config')->limit(0,1)->find();
        $access_token = $xcxConfig['access_token'];
        if (time() >= $xcxConfig['exp_time']) {
            $access_token_data = file_get_contents($url);
            $access_token_data = json_decode($access_token_data,true);
            $access_token = $access_token_data['access_token'];
            Db::name('xcx_config')->where('name','access_token')->update([
                'access_token'=>$access_token,
                'exp_time'=>time()+$lifeTime
            ]);
        }
        return ['code'=>200,'msg'=>'获取成功','data'=>["access_token"=>$access_token]];
    }
    /**
     * 获取公众号AccessToken
     */
    public static function getGzhAccessToken()
    {
        //获取access_token
        $config = Config::get("parameter.gzh_config");
        $appid = $config['gzh_app_id'];
        $secret = $config['gzh_app_secret'];
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $lifeTime = 2 * 3000;
        $xcxConfig = Db::name('gzh_config')->limit(0,1)->find();
        $access_token = $xcxConfig['access_token'];
        if (time() >= $xcxConfig['exp_time']) {
            $access_token_data = file_get_contents($url);
            $access_token_data = json_decode($access_token_data,true);
            $access_token = $access_token_data['access_token'];
            Db::name('gzh_config')->where('name','access_token')->update([
                'access_token'=>$access_token,
                'exp_time'=>time()+$lifeTime
            ]);
        }
        return ['code'=>200,'msg'=>'获取成功','data'=>["access_token"=>$access_token]];
    }
  
    /**
     * 文本内容安全识别
     */
    public static function TextRecognition($content,$openid)
    {
        $access_token_data = self::getAccessToken();
        if ($access_token_data["code"]!=200){
            return $access_token_data;
        }
        $access_token = $access_token_data["data"]["access_token"];
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=".$access_token;
        $data = [
            "content" => $content,
            "version" => 2,
            "scene" => 1,
            "openid" => $openid,
        ];
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $result = curlPost($url,$data);
        $result = json_decode($result,true);
        if($result['errcode'] == 0){
            $response = $result['result'];
            if($response['label'] != 100){
                $response_msg = "";
                switch ($response["label"]) {
                    case 10001:
                        $response_msg = "广告";
                        break;
                    case 20001:
                        $response_msg = "时政";
                        break;
                    case 20002:
                        $response_msg = "色情";
                        break;
                    case 20003:
                        $response_msg = "辱骂";
                        break;
                    case 20006:
                        $response_msg = "违法犯罪";
                        break;
                    case 20008:
                        $response_msg = "欺诈";
                        break;
                    case 20012:
                        $response_msg = "低俗";
                        break;
                    case 20013:
                        $response_msg = "版权";
                        break;
                    case 21000 :
                        $response_msg = "其它";
                        break;
                }
                return ['code'=>200,'label'=>$response['label'],'data'=>$response_msg];
            }else{
                return ['code'=>200,'label'=>$response['label'],'data'=>''];
            }
        }else{
            return ['code'=>201,'label'=>'请求失败','data'=>$result];
        }
    }

    /**
     * 音视频内容安全识别
     */
    public static function VideoRecognition($media_url,$media_type,$openid)
    {
        $access_token_data = self::getAccessToken();
        if ($access_token_data["code"]!=200){
            return $access_token_data;
        }
        $access_token = $access_token_data["data"]["access_token"];
        $url = "https://api.weixin.qq.com/wxa/media_check_async?access_token=".$access_token;
        $data = [
            "media_url" => $media_url,
            "media_type" => $media_type,
            "version" => 2,
            "scene" => 1,
            "openid" => $openid,
        ];
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $result = curlPost($url,$data);
        $result = json_decode($result,true);
        if($result['errcode'] == 0){
            if(isset($result['result'])){
                $response = $result['result'];
                if($response['label'] != 100){
                    $response_msg = "";
                    switch ($response["label"]) {
                        case 20001:
                            $response_msg = "时政";
                            break;
                        case 20002:
                            $response_msg = "色情";
                            break;
                        case 20006:
                            $response_msg = "违法犯罪";
                            break;
                        case 21000 :
                            $response_msg = "其它";
                            break;
                    }
                    return ['code'=>200,'label'=>$response['label'],'data'=>$response_msg];
                }else{
                    return ['code'=>200,'label'=>$response['label'],'data'=>''];
                }
            }else{
                return ['code'=>200,'label'=>100,'data'=>''];
            }
        }else{
            return ['code'=>201,'label'=>'请求失败','data'=>$result];
        }
    }

    /**
     * 获取小程序码
     * @param  [string] $page     [小程序地址]
     * @param  [string] $scene    [小程序地址页面参数]
     * @param  [string] $filePath [二维码文件地址]
     */
    public static function getWxCode($page,$scene,$filePath,$width)
    {
        if (!is_string($page)){
            return "小程序地址不能为空";
        }
        if (!is_string($filePath)){
            return "二维码文件地址不能为空";
        }
        $access_token_data = self::getAccessToken();
        $ACCESS_TOKEN = $access_token_data["data"]["access_token"];
        $url ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$ACCESS_TOKEN";
        $param_array = array(
            "page" => $page,
            "scene" => $scene,
            "width" => $width,
            "check_path" =>false,
            "env_version" => "trial",
            //'is_hyaline'=>true,
        );
        $param = json_encode($param_array);
        $result = curlPost($url,$param);
        $document_root_file = $_SERVER['DOCUMENT_ROOT'].$filePath;
        //检测目录是否存在
        if(!is_dir($document_root_file))
        {
            mkdir($document_root_file,0777,true);
        }
        file_put_contents($document_root_file.'/'.$scene.'.png', $result, true);
        return ["code"=>200,'msg'=>"生成成功","data"=>["file"=> $filePath.'/'.$scene.'.png']];
    }

    /**
     * 发送订阅消息
     */
    public function SubscribeSendPriceDifference($data)
    {
        $access_token_data = self::getAccessToken();
        if ($access_token_data["code"]!=200){
            return $access_token_data;
        }
        $token = $access_token_data['data']['access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        
        $send_data = [
            "touser" => $data['openid'],
            "access_token" => $token,
            "template_id" => "Hg6rrHje3fNwQcQvH8fXuVTIZWZ2Gnemh41o8DNnnh4",
            "page" => "pages/SupplementaryPay/SupplementaryPay",
            "data" => [
                "amount3" => [
                    "value" => number_format($data['restock_money'],2)
                ],
                "character_string2" => [
                    "value" => $data['order_number']
                ],
                "character_string5" => [
                  "value" => $data['logistics_number']
                ]
            ],
            "miniprogram_state" => "trial"
        ];

        $str_data = json_encode($send_data,320);
        $res = curlPost($url,$str_data);
        return $res;
    }
}